﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using HttpServer;
using CommandServer;
using ServerPattern;
using SyncedFileAccess;
using System.Threading;
using System.Runtime.InteropServices;
using RobotCtrl;

namespace MainEntry
{
    class MainEntry
    {
        private HttpServer.HttpServer httpServer;
        private SyncedFile sf;

        public static void Main()
        {
            MainEntry m = new MainEntry();
        }


        public MainEntry()
        {
            int port = 8080;
            String host = Dns.GetHostName();
            sf = new SyncedFile("ts2.txt");
            sf.WriteLine("Server started: " + DateTime.Now);

            httpServer = new HttpServer.HttpServer(sf);
            httpServer.Start(port, host);
            Console.WriteLine("FileServer gestartet");
            new CommandServer.CommandServer(new Robot(RunMode.REAL,sf)).Start();
            Console.WriteLine("CommandServer auf {0} gestartet.",
                ServerPattern.AbstractBTServer.DEFAULTSERVICE.ToString());

            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
            this.process_Exited();
        }

        private void process_Exited()
        {
            Console.WriteLine("Stopping server and closing file");
            httpServer.Stop();
            sf.Close();
            Console.WriteLine("Closed");
            Thread.Sleep(2000);
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
    }
}

/*
 * 
    [DllImport("coredll")]
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

    // A delegate type to be used as the handler routine
    // for SetConsoleCtrlHandler.
    public delegate bool HandlerRoutine(CtrlTypes CtrlType);

    // An enumerated type for the control messages
    // sent to the handler routine.
    public enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT,
        CTRL_CLOSE_EVENT,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT
    }

    private bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
        // Put your own handler here
        Console.WriteLine("Stopping server and closing file");
        httpServer.Stop();
        sf.Close();
        return true;
   }
 * 
 * //Register for console exit --> does not work under WinCE
            System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
            Console.WriteLine(process.EnableRaisingEvents);
            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(process_Exited);
            Console.WriteLine(process.EnableRaisingEvents);
            SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
     

 * 
*/